<script lang="jsx" setup>
import dayjs from 'dayjs';
import { computed, nextTick, onMounted, ref } from 'vue';
import { AppstoreOutlined, UnorderedListOutlined } from '@ant-design/icons-vue';
import { useElementSize } from '@vueuse/core';
import { Empty } from 'ant-design-vue';
import { UUID } from 'uuidjs';
import Table from '@/components/common/table.vue';
import CommonSearch from '@/components/common/common-search.vue';
import { getExceptionImgByUrl, getExceptionImgList } from '@/service/api/modules/trace/avi';

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;

const path = window.$utils.getRouteParams();

const url = ref(null);
url.value = `/qms/${path}/find`;

const commonSearchRef = ref(null);
const tableRef = ref(null);
const searchParams = ref({
  prodNo: null,
  lotId: null,
  time: getTime(),
  deviceNo: null,
  is_read: '0',
  bad: null
});

onMounted(() => {
  tableRef.value.getData(1);
});

function getTime() {
  const now = new Date();
  now.setHours(0, 0, 0, 0);
  const nowDateEndTamp = new Date().setHours(23, 59, 59, 999);
  const nowTimeStartTamp = now.getTime();
  return [dayjs(nowTimeStartTamp).format('YYYY-MM-DD HH:mm:ss'), dayjs(nowDateEndTamp).format('YYYY-MM-DD HH:mm:ss')];
}

const { height: commonSearchHeight } = useElementSize(commonSearchRef);

const computedCommonSearchHeight = computed(() => {
  return `calc(100% - ${commonSearchHeight.value}px)`;
});

// PNL编号 料号 LOT号

const searchFormList = [
  {
    type: 'input',
    key: 'deviceNo',
    label: '设备编码',
    placeholder: '请输入设备编码',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 6
  },

  {
    type: 'input',
    key: 'prodNo',
    label: '生产型号',
    placeholder: '请输入生产型号',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 6
  },
  {
    type: 'input',
    key: 'lotId',
    label: '批次号',
    placeholder: '请输入批次号',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 6
  },
  {
    type: 'input',
    key: 'bad',
    label: '异常名称',
    placeholder: '请输入异常名称',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 6
  },
  {
    type: 'select',
    key: 'is_read',
    label: '是否有码',
    placeholder: '请选择是否有码',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 6,
    selectOptions: [
      {
        label: '全部',
        value: '2'
      },
      {
        label: '有码',
        value: '0'
      },
      {
        label: '无码',
        value: '1'
      }
    ]
  },
  {
    type: 'dateRangePicker',
    key: 'time',
    label: '时间',
    span: 24,
    md: 12,
    lg: 10,
    xl: 8,
    xxl: 6,
    showTime: true
  }
];

const searchData = computed(() => {
  const params = {
    ...searchParams.value
  };
  if (searchParams.value?.time?.[0]) {
    params.startTime = dayjs(searchParams.value.time[0]).format('YYYY-MM-DD HH:mm:ss');
    params.endTime = dayjs(searchParams.value.time[1]).format('YYYY-MM-DD HH:mm:ss');
  }
  delete params.time;
  return params;
});

const column = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: 'deviceNo',
    dataIndex: 'deviceNo',
    title: '设备编号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 80
  },
  {
    key: 'setId',
    dataIndex: 'setId',
    title: 'SET编号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 200
  },
  {
    key: 'prodNo',
    dataIndex: 'prodNo',
    title: '生产型号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  // {
  //   key: 'lotId',
  //   dataIndex: 'lotId',
  //   title: 'Lot号',
  //   align: 'center',
  //   checked: true,
  //   ellipsis: true,
  //   width: 150
  // },
  {
    key: 'boardNo',
    dataIndex: 'boardNo',
    title: '板号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 165
  },
  {
    key: 'serial',
    dataIndex: 'serial',
    title: '序列号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 150
  },
  // {
  //   key: 'matName',
  //   dataIndex: 'matName',
  //   title: '物料名称',
  //   align: 'center',
  //   checked: true,
  //   ellipsis: true,
  //   width: 150
  // },
  // {
  //   key: 'deviceName',
  //   dataIndex: 'deviceName',
  //   title: '设备名称',
  //   align: 'center',
  //   checked: true,
  //   ellipsis: true,
  //   width: 150
  // },
  {
    key: 'upTime',
    dataIndex: 'upTime',
    title: '时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 180,
    customRender: ({ record }) => {
      return dayjs(record.upTime).format('YYYY-MM-DD HH:mm:ss');
    }
  }
];

function search() {
  nextTick(() => {
    tableRef.value.getData(1);
  });
}

function reset() {
  searchParams.value = {
    prodNo: null,
    lotId: null,
    time: getTime(),
    deviceNo: null,
    is_read: '0',
    bad: null
  };
  nextTick(() => {
    search();
  });
}

// 右侧
const activeKey = ref('1');

const defectTableColumn = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'defectsKind',
    dataIndex: 'defectsKind',
    title: '异常名称',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'defectsNum',
    dataIndex: 'defectsNum',
    title: '异常次数',
    align: 'center',
    checked: true,
    ellipsis: true,
    sorter: {
      compare: (a, b) => a.defectsNum - b.defectsNum,
      multiple: 2
    }
  }
];

// 分页相关
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(200);
const pageSizeOptions = ref(['50', '100', '200', '500', '1000', '2000']);
const positiveSideData = ref([]);
const positiveSideAbnormalCount = ref(0); // 正面异常总次数
const reverseSideData = ref([]);
const reverseSideAbnormalCount = ref(0); // 反面异常总次数
const showType = ref('table');
const imgList = ref([]);
const viewImgList = ref([]);
const imgContentRef = ref(null);
const currentLeftRow = ref(null);
function getImgList() {
  getExceptionImgList(
    {
      // path: `${currentLeftRow.value.path.replace('D:', '').replace(`\\`, '').replace(/\\/g, '/')}/`
      id: currentLeftRow.value.id
    },
    path
  ).then(({ data, error }) => {
    if (!error) {
      // console.log('图片信息：', data);
      imgList.value = data
        .filter(item => {
          const type = item.split('.')[1];
          return type === 'jpeg' || type === 'png' || type === 'gif' || type === 'jpg' || type === 'bmp';
        })

        .map(item => {
          // console.log('item', item);
          const splitArr = item.split('/');
          return {
            fileName: item,
            url: `/dev-api/qms/${path}/image?filename=${item}`,
            size: null,
            time: dayjs(currentLeftRow.value.upTime).format('YYYY-MM-DD HH:mm:ss'),
            imgFileName: splitArr[splitArr.length - 1]
          };
        });
      imgList.value.forEach((item, index) => {
        item.dataIndex = index + 1;
        item.tableUuid = UUID.genV4().hexNoDelim;
      });
      total.value = imgList.value.length;
      pageSizeOptions.value.push(data.length.toString());
      viewImgList.value = imgList.value.map(item => item.url);
    }
  });
}
function handleTableRowClick(row) {
  currentLeftRow.value = row;
  getExceptionImgByUrl({ id: row.id }, path).then(({ data, error }) => {
    if (!error) {
      const positiveSide = data.filter(item => Number(item.pn) === 0);
      const reverseSide = data.filter(item => Number(item.pn) === 1);
      positiveSide.forEach((item, index) => {
        item.dataIndex = index + 1;
      });
      reverseSide.forEach((item, index) => {
        item.dataIndex = index + 1;
      });
      positiveSideAbnormalCount.value = positiveSide.reduce((acc, cur) => acc + cur.defectsNum, 0);
      reverseSideAbnormalCount.value = reverseSide.reduce((acc, cur) => acc + cur.defectsNum, 0);
      positiveSideData.value = positiveSide;
      reverseSideData.value = reverseSide;
    }
  });
  getImgList();
}

let isFirst = 0;
function leftTableDataLoadSucess(data) {
  if (isFirst === 2) return;
  isFirst += 1;
  tableRef.value.setCurrentRowId(data[0]);
  currentLeftRow.value = data[0];
  // getImgList();
  handleTableRowClick(data[0]);
}

function typeChange() {
  pageNum.value = 1;
}
const imgTableColumns = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'imgFileName',
    dataIndex: 'imgFileName',
    title: '文件名称',
    align: 'center',
    checked: true,
    ellipsis: true,
    fixed: 'left',
    width: 150
  },
  {
    key: 'size',
    dataIndex: 'size',
    title: '文件大小',
    align: 'center',
    checked: true,
    ellipsis: true,
    fixed: 'left',
    width: 150
  },
  {
    key: 'time',
    dataIndex: 'time',
    title: '上传时间',
    align: 'center',
    fixed: 'left',
    checked: true,
    ellipsis: true,
    width: 180
  },
  {
    key: 'url',
    dataIndex: 'url',
    title: '图片',
    align: 'center',
    checked: true,
    fixed: 'left',
    ellipsis: true,
    width: 100,
    customRender: ({ record }) => {
      return (
        <div class="w-full flex-center cursor-pointer" onClick={() => handleViewImg(record.dataIndex - 1)}>
          <img width={22} src={record.url} alt="" key={record.url} />
        </div>
      );
    }
  }
];

// 预览图片
const viewImgVisible = ref(false);
const currentImgViewIndex = ref(0);
const modalImgRef = ref(null);
const imgScale = ref(1);
const rotate = ref(0);
function handleViewImg(index) {
  viewImgVisible.value = true;
  currentImgViewIndex.value = index;
}

const computedList = computed(() => {
  // 计算起始索引
  const startIndex = (pageNum.value - 1) * pageSize.value;
  // 计算结束索引
  const endIndex = startIndex + pageSize.value;

  // 截取出当前页的数据
  const paginatedData = imgList.value.slice(startIndex, endIndex);
  // console.log('paginatedData', paginatedData);

  return paginatedData;
});

const { height } = useElementSize(imgContentRef);

const tableScrollY = computed(() => {
  return height.value - 40;
});

function onChange(page, pageSizes) {
  pageNum.value = page;
  pageSize.value = pageSizes;
  imgContentRef.value.scrollTop = 0;
}

function handleNext() {
  if (currentImgViewIndex.value === imgList.value.length - 1) return;
  resetStyle();
  currentImgViewIndex.value += 1;
}

function handleImgPreviou() {
  if (currentImgViewIndex.value === 0) return;
  resetStyle();
  currentImgViewIndex.value -= 1;
}

function resetStyle() {
  imgScale.value = 1;
  rotate.value = 0;
}

function handleScale(type) {
  if (type === 'plus') {
    imgScale.value += 0.1;
  } else {
    imgScale.value -= 0.1;
  }
}

function handleScroll(event) {
  event.stopPropagation();

  if (event.deltaY < 0) {
    // 向上滚动放大
    imgScale.value += 0.1;
  } else {
    // 向下滚动缩小
    imgScale.value -= 0.1;
  }
}

function handleRotate(type) {
  if (type === 'left') {
    rotate.value -= 90;
  } else {
    rotate.value += 90;
  }
}

function handleViewImgClose() {
  viewImgVisible.value = false;
  resetStyle();
}

// const tableCustomRow = record => {
//   return {
//     style: {
//       background: record.image === false ? '#1E90FF' : ''
//     }
//   };
// };

const tableCustomCell = (record, columnData) => {
  if (columnData.key === 'prodNo' && record.image === false) {
    return {
      style: {
        background: '#1E90FF'
      }
    };
  }
  return {};
};
</script>

<template>
  <div class="aoi-trace-page jl-main-page min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <CommonSearch
      ref="commonSearchRef"
      v-model:searchParams="searchParams"
      :form-list="searchFormList"
      :is-search="true"
      @search="search"
      @reset="reset"
    ></CommonSearch>

    <ARow :gutter="8" :style="{ height: computedCommonSearchHeight }">
      <ACol :span="10" class="h-full">
        <Table
          ref="tableRef"
          v-model:searchParams="searchData"
          :column="column"
          :show-row-selection="false"
          row-key="id"
          :scroll="{ y: 'auto' }"
          class="h-full"
          :url="url"
          :is-init-get-data="false"
          :table-custom-cell="tableCustomCell"
          @table-row-click="handleTableRowClick"
          @table-data-load-sucess="leftTableDataLoadSucess"
        >
          <template #title>
            <div class="flex-center gap-15px">
              <div class="mt-5px flex line-height-14px">
                <div class="h14px w20px bg-#1E90FF"></div>
                <span class="font-bold" style="font-size: 14px">待上传异常图片</span>
              </div>
            </div>
          </template>
        </Table>
      </ACol>

      <ACol :span="14" class="h-full">
        <div class="title bg-#fff pl8px text-size-18px color-blue-600 font-bold">
          <template v-if="currentLeftRow">
            <span class="color-black">SET编号:</span>
            {{ currentLeftRow?.setId }}
            <span class="color-black">异常明细</span>
          </template>
        </div>
        <div class="right">
          <div class="defect-list h40% flex justify-between">
            <div class="positive-side w-full">
              <ATabs v-model:activeKey="activeKey" size="small" type="card">
                <ATabPane key="1" tab="正面异常明细">
                  <STable
                    :columns="defectTableColumn"
                    :pagination="false"
                    :data-source="positiveSideData"
                    size="small"
                    row-key="id"
                    :row-height="23"
                    class="no-has-pagination-table has-footer-table h-full"
                    bordered
                    summary-fixed
                  >
                    <template #summary>
                      <STableSummaryRow>
                        <STableSummaryCell :index="0" :col-span="2" class="text-center color-blue-600 font-bold">
                          总异常次数
                        </STableSummaryCell>

                        <STableSummaryCell :index="1" class="text-center color-blue-600 font-bold">
                          {{ positiveSideAbnormalCount }}
                        </STableSummaryCell>
                      </STableSummaryRow>
                    </template>
                  </STable>
                </ATabPane>

                <ATabPane key="2" tab="反面异常明细">
                  <STable
                    :columns="defectTableColumn"
                    :pagination="false"
                    :data-source="reverseSideData"
                    size="small"
                    row-key="id"
                    class="no-has-pagination-table has-footer-table h-full"
                    :row-height="23"
                    bordered
                    summary-fixed
                  >
                    <template #summary>
                      <STableSummaryRow>
                        <STableSummaryCell :index="0" :col-span="2" class="text-center color-blue-600 font-bold">
                          总异常次数
                        </STableSummaryCell>

                        <STableSummaryCell :index="1" class="text-center color-blue-600 font-bold">
                          {{ reverseSideAbnormalCount }}
                        </STableSummaryCell>
                      </STableSummaryRow>
                    </template>
                  </STable>
                </ATabPane>
              </ATabs>
            </div>
          </div>
          <div class="img-list h60% w-full">
            <ATabs size="small" type="card">
              <ATabPane key="1" tab="图片信息"></ATabPane>
            </ATabs>
            <div class="change-type">
              <div class="show-type center flex">
                <div class="lable mr-5px">
                  <span>显示形式:</span>
                </div>
                <ARadioGroup v-model:value="showType" size="small" @change="typeChange">
                  <ARadioButton value="table">
                    <UnorderedListOutlined />
                  </ARadioButton>
                  <ARadioButton value="list">
                    <AppstoreOutlined />
                  </ARadioButton>
                </ARadioGroup>
              </div>
            </div>

            <div ref="imgContentRef" class="img-content w-full">
              <template v-if="showType === 'list'">
                <template v-if="computedList.length">
                  <div class="img-list h-full w-full overflow-auto">
                    <template v-for="(item, index) in computedList" :key="item.url">
                      <div class="img-item" @click="handleViewImg(index)">
                        <ATooltip placement="right">
                          <img v-lazy="item.url" alt="" />
                          <template #title>
                            <div class="img-data">
                              <div class="data-item flex">
                                <div class="label">文件名称:</div>
                                <div class="value">{{ item.imgFileName }}</div>
                              </div>
                              <div class="data-item flex">
                                <div class="label">文件大小:</div>
                                <div class="value">{{ item.size }}</div>
                              </div>
                              <div class="data-item flex">
                                <div class="label">时间:</div>
                                <div class="value">{{ item.time }}</div>
                              </div>
                            </div>
                          </template>
                        </ATooltip>
                        <div class="img-desc">{{ item.imgFileName }}</div>
                      </div>
                    </template>
                  </div>
                </template>
                <template v-else>
                  <div class="h-full w-full flex flex-center">
                    <AEmpty :image="simpleImage" />
                  </div>
                </template>
              </template>

              <!-- <div  class="h-full w-full table"> -->
              <STable
                v-if="showType === 'table'"
                :data-source="computedList"
                :columns="imgTableColumns"
                size="small"
                :pagination="false"
                row-key="tableUuid"
                :show-row-selection="false"
                :scroll="{ y: tableScrollY }"
                class="no-has-pagination-table img-table h-full w-full"
                bordered
              ></STable>
              <!-- </div> -->
            </div>
            <div class="pagination mt-8px flex justify-end">
              <APagination
                v-model:current="pageNum"
                v-model:page-size="pageSize"
                show-size-changer
                show-quick-jumper
                :total="total"
                :page-size-options="pageSizeOptions"
                size="small"
                :show-header="false"
                @change="onChange"
              />
            </div>
          </div>
        </div>
      </ACol>
    </ARow>

    <Modal
      v-model:visible="viewImgVisible"
      :title="computedList?.[currentImgViewIndex]?.imgFileName"
      width="750px"
      height="650px"
      :destroy-on-close="true"
      @close="handleViewImgClose"
    >
      <div class="view-img-content" @wheel="handleScroll">
        <img
          ref="modalImgRef"
          :style="{ transform: ` translate(-50%, -50%) scale(${imgScale}) rotate(${rotate}deg)` }"
          :src="viewImgList[currentImgViewIndex]"
          alt=""
        />
      </div>
      <template #footer>
        <div class="modal-footer">
          <AButton @click="handleRotate('left')">左旋转</AButton>
          <AButton @click="handleRotate('right')">右旋转</AButton>
          <AButton @click="handleScale('plus')">放大</AButton>
          <AButton @click="handleScale('minus')">缩小</AButton>
          <AButton @click="handleImgPreviou">上一张</AButton>
          <AButton @click="handleNext">下一张</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style lang="scss" scoped>
.aoi-trace-page {
  :deep(.ant-tabs) {
    .ant-tabs-nav {
      margin-bottom: 3px;
    }
    .ant-tabs-content-holder {
      height: calc(100% - 38px);
    }
  }
  .right {
    background-color: #fff;
    border-radius: 10px;
    padding: 0 8px;
    height: calc(100% - 29px);

    :deep(.surely-table-wrapper) {
      &.has-footer-table {
        .ant-spin-nested-loading {
          .ant-spin-container {
            .surely-table {
              height: 100%;
            }
          }
        }
      }
    }

    .defect-list {
      // .defect-table {
      //   height: calc(100% - 38px);
      // }
      .positive-side {
        :deep(.ant-tabs) {
          height: 100%;
          .ant-tabs-content {
            height: 100%;
          }
        }
      }
    }
    .img-list {
      position: relative;
      .change-type {
        position: absolute;
        top: 10px;
        right: 10px;
      }

      // :deep(.ant-table-wrapper) {
      //   .ant-table {
      //     height: 100% !important;
      //   }
      // }

      .img-content {
        height: calc(100% - 82px);
        .img-list {
          padding: 15px;
          display: flex;
          flex-wrap: wrap;
          gap: 10px;

          .img-item {
            width: 80px;
            height: 100px;
            padding: 10px;
            box-sizing: border-box;

            &:hover {
              background: #f0f9f7 !important;
              cursor: pointer;
              // border: 1px solid #ddefeb;
            }

            .img-desc {
              white-space: nowrap;
              /* 强制文本在一行内显示 */
              overflow: hidden;
              /* 隐藏溢出的内容 */
              text-overflow: ellipsis;
              /* 显示省略号 */
              text-align: center;
            }
          }
        }
        .table {
          :deep(.ant-card) {
            .ant-card-body {
              padding-bottom: 0;
            }
          }
        }
      }
    }
  }
}

.view-img-content {
  width: 100%;
  height: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  position: relative;
  overflow: hidden;
  img {
    position: absolute;
    top: 50%;
    left: 50%;
    transition: all 200ms;
    transform: translate(-50%, -50%);
  }
}
</style>
